/**
 * Created by lvzj on 2015/6/20.
 */

var backofficeUserBehavior = mongoose.model('backoffice_user_behavior');
var User = mongoose.model('user');
exports.saveBehavior = function (req, res, next) {

    if (req.session.backOfficeUser != null) {
        var ip = (req.headers['x-forwarded-for'] || '').split(',')[0]
            || req.connection.remoteAddress;
        var uid = req.session.backOfficeUser._id;

        var params = {
            ip: ip,
            userId: uid,
            reqUrl: req.url,
            input: JSON.stringify(req.body)
        };

        var bub = new backofficeUserBehavior(params);

        bub.save();
    }
    next();
};

//1-版主 2-物业 3-雷锋团 4-创始人
exports.isModerator = function(userId,userRole,callback)
{
    var opt = {
        _id:userId,
        userRole:userRole
    }
    User.findOne(opt,'_id').exec(callback);
}

exports.checkAuth = function (req, res, next) {

    var url = req.url;
    logger.info(url);

    if(req.body.userId){
        exports.isModerator(req.body.userId,1,function()
        {
            logger.debug('user is moderator');
            next();
        })
    }else if (req.session.account == null && url.indexOf('admin/login') < 0 && url.indexOf('backoffice/question')< 0 && url.indexOf('backoffice/Systems/getSystemConfig')< 0) {
        var returnMessage = {
            "result": {
                "status": 9,
                "message": "用户登陆超时，请重新登陆"
            },
            "data": null
        }
        res.json(returnMessage);
    } else {
        next();
    }
};